import bindAll from 'lodash.bindall';
import React from 'react';
import {connect} from 'react-redux';

import {defaultProjectId, setProjectId, setLessonId} from '../reducers/project-state';

/* 高阶组件：从location.hash中获取作品ID
 * @param {React.Component} WrappedComponent: component to render
 * @returns {React.Component} component with hash parsing behavior
 */
const HashParserHOC = function (WrappedComponent) {
    class HashParserComponent extends React.Component {
        constructor (props) {
            super(props);
            bindAll(this, ['handleHashChange']);
        }
        componentDidMount () {
            window.addEventListener('hashchange', this.handleHashChange);
            this.handleHashChange();

            //第一次打开时，获取课时ID，并设置状态。location.search配置的lid=xxx,xxx为数字，即为ID
            const lesson_id = window.location.search.match(/lid=(\d+)/);
            if (lesson_id){
                this.props.onSetLessonId(parseInt(lesson_id[1]));
            } else {
                this.props.onSetLessonId(0);
            }
        }
        componentWillUnmount () {
            window.removeEventListener('hashchange', this.handleHashChange);
        }
        //获取Scratch项目ID，并设置状态。location.hash配置的#xxx,xxx为数字，即为ID
        handleHashChange () {
            const hashMatch = window.location.hash.match(/#(\d+)/);
            const hashProjectId = hashMatch === null ? defaultProjectId : hashMatch[1];
            //console.log("BLJ:Hash Parser分析到的作品ID："+hashProjectId);
            this.props.onSetProjectId(parseInt(hashProjectId));
        }

        render () {return <WrappedComponent/>}
    }
    //HashParserComponent.propTypes = {};
    const mapStateToProps = state => {return {}};
    const mapDispatchToProps = dispatch => ({
        onSetLessonId: lid => dispatch(setLessonId(lid)),
        onSetProjectId: projectId => dispatch(setProjectId(projectId)),
    });
    // Allow incoming props to override redux-provided props. Used to mock in tests.
    const mergeProps = (stateProps, dispatchProps, ownProps) => Object.assign(
        {}, stateProps, dispatchProps, ownProps
    );
    return connect(
        mapStateToProps,
        mapDispatchToProps,
        mergeProps
    )(HashParserComponent);
};

export {
    HashParserHOC as default
};
